package com.skit.main.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import com.skit.common.base.BaseActivity
import com.skit.common.bean.ActivityBean
import com.skit.common.config.RetrofitClient
import com.skit.common.http.HttpUtils
import com.skit.common.manager.UserManager
import com.skit.common.utils.ToastUtils
import com.skit.common.bean.ApplyBean
import com.skit.main.adapter.ApplyManageAdapter
import com.skit.main.databinding.MainActivityManageBinding
import com.skit.common.retrofit.ActivityProtocol
import kotlinx.android.synthetic.main.main_activity_manage.*
import java.util.*

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since  2020/6/4
 */
class ManageActivity : BaseActivity() {
    val binding: MainActivityManageBinding by lazy {
        MainActivityManageBinding.inflate(
            layoutInflater
        ).apply {
            lifecycleOwner = this@ManageActivity
        }
    }
    var aid: Int = 0
    var type: String = "all"
    private val applyBean: MutableList<ApplyBean> = ArrayList()
    private val backUpList: MutableList<ApplyBean> = ArrayList()
    private val filterList: MutableList<ApplyBean> = ArrayList()
    lateinit var adapter: ApplyManageAdapter
    lateinit var activityBean: ActivityBean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initViews()
        getData()
    }

    private fun initViews() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        editText2.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                val filter =
                    backUpList.filter { applyBean ->
                        applyBean.user.userInfo.stuID.startsWith(s.toString()) || applyBean.user.name.startsWith(
                            s.toString()
                        )
                    }
                applyBean.clear()
                applyBean.addAll(filter)
                adapter.notifyDataSetChanged()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })

        adapter = ApplyManageAdapter(applyBean)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)
        activityBean = intent.getSerializableExtra("bean") as ActivityBean
        aid = activityBean.id

        adapter.onItemClickListener = object : (Int, ApplyBean) -> Unit {
            override fun invoke(p1: Int, p2: ApplyBean) {
                if (activityBean.founderID != UserManager.user!!.id && p2.status == 3) {
                    ToastUtils.showToast("你没有权限对组织者进行操作")
                    return
                }

                if (activityBean.endTime < System.currentTimeMillis()) {
                    val arrayOf = arrayOf("发放学分")

                    val alertDialog: AlertDialog.Builder =
                        AlertDialog.Builder(this@ManageActivity).setItems(
                            arrayOf
                        ) { dialog, which ->
                            run {
                                ToastUtils.showToast("还未写")
                                /*var status = which
                                val service =
                                    RetrofitClient.getService(ActivityProtocol::class.java)
                                val call =
                                    service.checkApply(
                                        applyBean[p1].uid,
                                        aid,
                                        status,
                                        UserManager.user?.id!!
                                    )
                                HttpUtils.doRequest(call) {
                                    if (it == null || !it.isSuccess) {
                                        if (it != null) ToastUtils.showToast(it.msg)
                                        return@doRequest
                                    }
                                    ToastUtils.showToast("成功")
                                    applyBean[p1].status = status
                                    adapter.notifyItemChanged(p1)
                                }*/
                            }
                        }
                    alertDialog.show()
                    return
                }

                val arrayOf = if (activityBean.founderID == UserManager.user!!.id) arrayOf(
                    "待审核",
                    "拒绝申请",
                    "通过申请",
                    "设置为组织者"
                ) else arrayOf("待审核", "拒绝申请", "通过申请")

                val alertDialog: AlertDialog.Builder =
                    AlertDialog.Builder(this@ManageActivity).setItems(
                        arrayOf
                    ) { dialog, which ->
                        run {
                            var status = which
                            val service =
                                RetrofitClient.getService(ActivityProtocol::class.java)
                            val call =
                                service.checkApply(
                                    applyBean[p1].uid,
                                    aid,
                                    status,
                                    UserManager.user?.id!!
                                )
                            HttpUtils.doRequest(call) {
                                if (it == null || !it.isSuccess) {
                                    if (it != null) ToastUtils.showToast(it.msg)
                                    return@doRequest
                                }
                                ToastUtils.showToast("成功")
                                applyBean[p1].status = status
                                backUpList[p1].status = status
                                adapter.notifyItemChanged(p1)
                            }
                        }
                    }
                alertDialog.show()
            }


        }
    }

    fun getData() {
        progressBar.visibility = View.VISIBLE
        val userProtocol: ActivityProtocol = RetrofitClient.getService(ActivityProtocol::class.java)
        val call =
            userProtocol.getApplyList(aid, type)
        HttpUtils.doRequest(call) {
            progressBar.visibility = View.GONE
            if (it == null || !it.isSuccess) {
                if (it != null) ToastUtils.showToast(it.msg)
                return@doRequest
            }
            applyBean.clear()

            if (activityBean.endTime < System.currentTimeMillis()) {
                it.data.filter { applyBean -> applyBean.status >= 2 }.apply {
                    applyBean.addAll(this)
                    backUpList.addAll(this)
                }
            } else {
                applyBean.addAll(it.data)
                backUpList.addAll(it.data)
            }


            binding.flEmptyContainer.visibility =
                if (applyBean.isEmpty()) View.VISIBLE else View.GONE
            binding.editText2.visibility =
                if (applyBean.isNotEmpty()) View.VISIBLE else View.GONE
            adapter.notifyDataSetChanged()
        }
    }

    companion object {
        @JvmStatic
        fun startActivity(context: Context, activityBean: ActivityBean?) {
            val intent = Intent(context, ManageActivity::class.java)
            intent.putExtra("bean", activityBean)
            context.startActivity(intent)
        }

    }

}